/**
 * Created by zahir on 2015/4/2.
 */
var Q = require('q');
var models = require('../models');
var OrderModel = models.OrderModel;


function OrderDao() {

}

OrderDao.prototype.insertOrder = function (order) {
    var defferred = Q.defer();
    var orderModel = new OrderModel();

    orderModel.FCHANNELSORDERNO = order.channelsOrderNo;
    orderModel.FPLACEORDERTIME = order.placeOrderTime;
    orderModel.FLEASEBEGINTIME = order.leaseBeginTime;
    orderModel.FLEASEENDTIME = order.leaseEndTime;
    orderModel.FORDERREAMK1 = order.orderReamk1;
    orderModel.FDEVICEQUANTITY = order.deviceQuantity;
    orderModel.FLEASEDAYNUMBER = order.leaseDayNumber;
    orderModel.FCHANNELCOMPAYNAME = order.channelCompanyName;
    orderModel.FEXPRESSRECIPIENT = order.expressRecipient;
    orderModel.FEXPRESSRECIPIENTTEL = order.expressRecipientTel;
    orderModel.FRECEIVEADDRESS = order.receiveAddress;
    orderModel.FFOREGIFTSTATUS = order.foregitStatus;
    orderModel.FRESTITUTIONADDRESS = order.restitutionAddress;
    orderModel.FFOREGIFT = order.foregift;
    orderModel.FBATCHID = order.batchID,
        orderModel.FTAKEAWAYTIME = order.takeAwayTime,
        orderModel.FRENTMACHINEORDERNO = order.rentMachineOrderNo;
    orderModel.FORDERSTATUS = order.orderStatus;
    orderModel.FEXWAREHOUSETIME = order.exWareHouseTime;
    orderModel.FORDERREAMK2 = order.orderReamk2;
    orderModel.FORDERREAMK3 = order.orderReamk3;
    orderModel.FORDERREAMK4 = order.orderReamk4;
    orderModel.FCANCELDESCRIPTION = order.cancelDescription;

    orderModel.FDEVICETYPE = order.deviceType;
    orderModel.FPAYMENTMETHOD = order.paymentMehtod;
    orderModel.FPROCESSINGMODE = order.processingMode;
    orderModel.FDESTINATION = order.destination;
    orderModel.FUNITPRICE = order.unitPrice;
    orderModel.FEXPECTEDRENT = order.expectedRent;
    orderModel.FACTUALRENT = order.actualRent;
    orderModel.FTOTALRENT = order.totalRent;
    orderModel.FINWAREHOUSETIME = order.inWareHouseTime;
    orderModel.FRENEWAL = order.renewal;
    orderModel.FRENEWALTIME = order.renewalTime;
    orderModel.FACCOUNTS = order.accounts;
    orderModel.FSKYROAMID = order.skyroamID;
    orderModel.FCHANNELNO = order.channelNo;

    orderModel.FDELIVERYWAY = order.deliveryWay;
    orderModel.FDELIVERYPLACE = order.deliveryPlace;
    orderModel.FEXPRESSCOMPANY = order.expressCompany;

    orderModel.FEXPRESSPICKUPTIME = order.expressPickUpTime;
    orderModel.FEXPRESSNO = order.expressNo;
    orderModel.FEXPRESSSERVICETIME = order.expressServiceTime;
    orderModel.FCURRENCY = order.currency;
    orderModel.FCHECKEDSTATUS = order.checkedStatus;
    orderModel.FPROCESSINGMODE = order.processingModel
    orderModel.FDEDUCTFOREGIFT = order.deductForegift;
    orderModel.FDEDUCTFOREGIFTDESCRIPTION = order.deductForegiftDescription;
    orderModel.FDEDUCTFOREGIFTTIME = order.dedcutForegitftTime;
    orderModel.FDEVICELIST = order.deviceList

    orderModel.save(function (err, data) {
        if (err) {
            defferred.reject(err);
        } else {
            defferred.resolve(data);
        }
    });
    return defferred.promise;
}


OrderDao.prototype.deleteOrder = function (orderID) {
    var defferred = Q.defer();
    OrderModel.remove({_id: orderID}, function (err, data) {
        if (err) {
            defferred.reject(err);
        } else {
            defferred.resolve(data);
        }
    });
    return defferred.promise;
}

OrderDao.prototype.deleteOrderByBatchID = function (batchID) {
    var defferred = Q.defer();
    OrderModel.remove({FBATCHID: batchID},function (err, data) {
        if (err) {
            defferred.reject(err);
        } else {
            defferred.resolve(data);
        }
    });
    return defferred.promise;
}

OrderDao.prototype.findOrderInfoByOrderID = function(orderID){
    var defferred = Q.defer();
    OrderModel.findOne({_id: orderID}, {}, function (err, order) {
        if(err){
            defferred.reject(err);
        }else{
            defferred.resolve(order);
        }
    });
    return defferred.promise;
}

OrderDao.prototype.findOrderByConditions = function (conditions, option) {
    var defferred = Q.defer(),
        selectedParams = new Object();
    if (conditions.batchID)
        selectedParams.FBATCHID = conditions.batchID
    if (conditions.channelsOrderNo)
        selectedParams.FCHANNELSORDERNO = conditions.channelsOrderNo
    if (conditions.expressRecipient)
        selectedParams.FEXPRESSRECIPIENT = conditions.expressRecipient;
    if (conditions.expressRecipientTel)
        selectedParams.FEXPRESSRECIPIENTTEL = conditions.expressRecipientTel;
    if (conditions.sn) {
        selectedParams['FDEVICELIST.FSN'] = conditions.sn;
    }

    if (conditions.receiveAddress)
        selectedParams.FRECEIVEADDRESS = conditions.receiveAddress;
    if (conditions.takeAwayTime)
        selectedParams.FTAKEAWAYTIME = {$gte: conditions.takeAwayTime};
    if (conditions.exWareHouseBeginTime || conditions.exWareHouseEndTime)
        selectedParams['FDEVICELIST.FEXWAREHOUSETIME'] = {$gte: conditions.exWareHouseBeginTime || new Date(1000,01,01),$lte:conditions.exWareHouseEndTime || new Date(3000,01,01)};


//    if (conditions.leaseDayNumber)
//        selectedParams.FLEASEDAYNUMBER = {$gte:conditions.leaseDayNumber};
    console.log(selectedParams)
    OrderModel.find(
        selectedParams,
        {},
        {sort: undefined, limit: option.pageSize, skip: option.startAt}, function (err, data) {
            if (err) {
                defferred.reject(err);
            } else {
                defferred.resolve(data);
            }
        });
    return defferred.promise;
}

/*double check 过程   根据批次id 更改订单审核结果，并且更改文件状态*/
OrderDao.prototype.auditOrder = function (batchID) {
    var defferred = Q.defer();
    OrderModel.update({FBATCHID: batchID}, {$set: {'FAUDITRESULTS': true}}, { multi: true }, function (err, data) {
        if (err) {
            defferred.reject(err);
        } else {
            defferred.resolve(data);
        }
    });
    return defferred.promise;
}


OrderDao.prototype.updateOrder = function (order) {
    var defferred = Q.defer();
    OrderModel.findOne({_id: order._id}, {}, function (err, orderModel) {

        orderModel.FCHANNELSORDERNO = order.channelsOrderNo || orderModel.FCHANNELSORDERNO;
        orderModel.FPLACEORDERTIME = order.placeOrderTime || orderModel.FPLACEORDERTIME;
        orderModel.FLEASEBEGINTIME = order.leaseBeginTime || orderModel.FLEASEBEGINTIME;
        orderModel.FLEASEENDTIME = order.leaseEndTime || orderModel.FLEASEENDTIME;
        orderModel.FORDERREAMK1 = order.orderReamk1 || orderModel.FORDERREAMK1;
        orderModel.FDEVICEQUANTITY = order.deviceQuantity || orderModel.FDEVICEQUANTITY;
        orderModel.FLEASEDAYNUMBER = order.leaseDayNumber || orderModel.FLEASEDAYNUMBER;
        orderModel.FCHANNELCOMPAYNAME = order.channelCompanyName || orderModel.FCHANNELCOMPAYNAME;
        orderModel.FEXPRESSRECIPIENT = order.expressRecipient || orderModel.FEXPRESSRECIPIENT;
        orderModel.FEXPRESSRECIPIENTTEL = order.expressRecipientTel || orderModel.FEXPRESSRECIPIENTTEL;
        orderModel.FRECEIVEADDRESS = order.receiveAddress || orderModel.FRECEIVEADDRESS;
        orderModel.FFOREGIFTSTATUS = order.foregitStatus || orderModel.FFOREGIFTSTATUS;
        orderModel.FRESTITUTIONADDRESS = order.restitutionAddress || orderModel.FRESTITUTIONADDRESS;
        orderModel.FFOREGIFT = order.foregift || orderModel.FFOREGIFT;
        orderModel.FBATCHID = order.batchID || orderModel.FBATCHID,
        orderModel.FTAKEAWAYTIME = order.takeAwayTime || orderModel.FTAKEAWAYTIME,
        orderModel.FRENTMACHINEORDERNO = order.rentMachineOrderNo || orderModel.FRENTMACHINEORDERNO;
        orderModel.FORDERSTATUS = order.orderStatus || orderModel.FORDERSTATUS;
        orderModel.FEXWAREHOUSETIME = order.exWareHouseTime || orderModel.FEXWAREHOUSETIME;
        orderModel.FORDERREAMK2 = order.orderReamk2 || orderModel.FORDERREAMK2;
        orderModel.FORDERREAMK3 = order.orderReamk3 || orderModel.FORDERREAMK3;
        orderModel.FORDERREAMK4 = order.orderReamk4 || orderModel.FORDERREAMK4;
        orderModel.FCANCELDESCRIPTION = order.cancelDescription || orderModel.FCANCELDESCRIPTION;

        orderModel.FDEVICETYPE = order.deviceType || orderModel.FDEVICETYPE;
        orderModel.FPAYMENTMETHOD = order.paymentMehtod || orderModel.FPAYMENTMETHOD;
        orderModel.FPROCESSINGMODE = order.processingMode || orderModel.FPROCESSINGMODE;
        orderModel.FDESTINATION = order.destination || orderModel.FDESTINATION;
        orderModel.FUNITPRICE = order.unitPrice || orderModel.FUNITPRICE;
        orderModel.FEXPECTEDRENT = order.expectedRent || orderModel.FEXPECTEDRENT;
        orderModel.FACTUALRENT = order.actualRent || orderModel.FACTUALRENT;
        orderModel.FTOTALRENT = order.totalRent || orderModel.FTOTALRENT;
        orderModel.FINWAREHOUSETIME = order.inWareHouseTime || orderModel.FINWAREHOUSETIME;
        orderModel.FRENEWAL = order.renewal || orderModel.FRENEWAL;
        orderModel.FRENEWALTIME = order.renewalTime || orderModel.FRENEWALTIME;
        orderModel.FACCOUNTS = order.accounts || orderModel.FACCOUNTS;
        orderModel.FSKYROAMID = order.skyroamID || orderModel.FSKYROAMID;
        orderModel.FCHANNELNO = order.channelNo || orderModel.FCHANNELNO;

        orderModel.FDELIVERYWAY = order.deliveryWay || orderModel.FDELIVERYWAY;
        orderModel.FDELIVERYPLACE = order.deliveryPlace || orderModel.FDELIVERYPLACE;
        orderModel.FEXPRESSCOMPANY = order.expressCompany || orderModel.FEXPRESSCOMPANY;

        orderModel.FEXPRESSPICKUPTIME = order.expressPickUpTime || orderModel.FEXPRESSPICKUPTIME;
        orderModel.FEXPRESSNO = order.expressNo || orderModel.FEXPRESSNO;
        orderModel.FEXPRESSSERVICETIME = order.expressServiceTime || orderModel.FEXPRESSSERVICETIME;
        orderModel.FCURRENCY = order.currency || orderModel.FCURRENCY;
        orderModel.FCHECKEDSTATUS = order.checkedStatus || orderModel.FCHECKEDSTATUS;
        orderModel.FPROCESSINGMODE = order.processingModel || orderModel.FPROCESSINGMODE;
        orderModel.FDEDUCTFOREGIFT = order.deductForegift || orderModel.FDEDUCTFOREGIFT;
        orderModel.FDEDUCTFOREGIFTDESCRIPTION = order.deductForegiftDescription || orderModel.FDEDUCTFOREGIFTDESCRIPTION;
        orderModel.FDEDUCTFOREGIFTTIME = order.dedcutForegitftTime || orderModel.FDEDUCTFOREGIFTTIME;

        if (err) {
            defferred.reject(err);
        } else {
            orderModel.FDEVICELIST = order.FDEVICELIST || orderModel.FDEVICELIST
            orderModel.markModified('anything');
            orderModel.save(function (err, data) {
                if (err) {
                    defferred.reject(err);
                } else {
                    defferred.resolve(data);
                }
            });

        }

    });
    return defferred.promise;
}

OrderDao.prototype.updateOrderTemp = function (order) {
    var defferred = Q.defer();
    OrderModel.findOne({_id: order._id}, {}, function (err, orderModel) {
        if (err) {
            defferred.reject(err);
        } else {

            for(var key in orderModel){
                if(order[key]){
                    orderModel[key] = order[key];
                }
            }
            orderModel.markModified('anything');
            orderModel.save(function (err, data) {
                if (err) {
                    defferred.reject(err);
                } else {
                    defferred.resolve(data);
                }
            });

        }

    });
    return defferred.promise;
}

/*---------------------测试方法------------------*/
OrderDao.prototype.push = function (id) {
    var defferred = Q.defer();
    OrderModel.update({_id: id}, {$push: {'FDEVICELIST': {FSN: '22222'}}}, {safe: true, multi: true}, function (err, data) {
        console.log(err, data)
    });
    return defferred.promise;
}

OrderDao.prototype.updatelist = function (id) {
    var defferred = Q.defer();
    OrderModel.update({_id: id, 'FDEVICELIST.FSN': '11111'}, {$set: {'FDEVICELIST.$.FSKU': '2222'}}, {safe: true, multi: true}, function (err, data) {
        console.log(err, data)
    });
    return defferred.promise;
}

OrderDao.prototype.updateBucklist = function (id) {
    var defferred = Q.defer();
    OrderModel.findOne({_id: id}, {}, function (err, data) {
        console.log(err, data);
        data.FDEVICELIST.forEach(function (deivce) {
            deivce.FSKU = '5555';
        });
        data.markModified('anything');
        data.save();
    });
    return defferred.promise;
}

OrderDao.prototype.dellist = function (id) {
    var defferred = Q.defer();
    OrderModel.update({_id: id}, {$pull: {'FDEVICELIST': {'FSN': '11111'}}}, false, function (err, data) {
        console.log(err, data)
    });
    return defferred.promise;
}

exports.OrderDao = OrderDao;


//new OrderDao().push('55b1dd107c619e6c18e7f89d')
//new OrderDao().deleteOrder('55b1dd107c619e6c18e7f89c').then(function(err,data){
//    console.log(err,data);
//});




